package com.hunt.app.task;

import com.hunt.service.OnlineStatisticsTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * @author ww
 * @className
 * @description
 * @date 2020/6/22
 */
@Component
public class OnlineStatisticsTask {
    
    private static final Logger log = LoggerFactory.getLogger(OnlineStatisticsTask.class);
    
    private static final String TIMER_KEY = "TIMER_KEY";
    
    @Autowired
    private OnlineStatisticsTaskService onlineStatisticsTaskService;
    
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    //三十分钟更新一下
    @Scheduled(cron = "0 0/30 * * * ? ")
    public void taskStarter() {
        //集群部署情况做分布式锁抢占式 返回true抢到了锁  返回false没抢到直接return
        Boolean b = redisTemplate.opsForValue().setIfAbsent(TIMER_KEY, "The_timer_is_Executing");
        //10分钟移除标志防止线程卡死去不掉
        redisTemplate.expire("The_timer_is_Executing",10, TimeUnit.MINUTES);
        if (b){
            log.info("OnlineStatistics Task invoked");
            try {
                onlineStatisticsTaskService.getAllOnlineUser();
            } catch (Exception e) {
                redisTemplate.delete(TIMER_KEY);
                log.info("OnlineStatistics timer execute failed and release Lock! System error!");
                e.printStackTrace();
            }
            //执行完毕释放锁
            redisTemplate.delete(TIMER_KEY);
            log.info("OnlineStatistics timer execute success and release Lock!");
        }
    }
}
